package com.koro.filter;

import com.koro.entity.LoginUser;
import com.koro.service.impl.LoginUsersService;
import com.koro.tool.SecurityJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class SecurityJwtFilter extends OncePerRequestFilter {
    @Resource
    private LoginUsersService loginUsersService;
    @Resource
    private SecurityJwtUtil securityJwtUtil;

    private final String Authorization = "token";
    private final String tokenHead = "Bearer";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        //拿到Authorization请求头内的Header信息
        String authHeader = request.getHeader(Authorization);

        //判断一下内容是否为空且是否为(Bearer)开头
        if (authHeader != null && authHeader.startsWith(tokenHead)) {

            //去掉token前缀(Bearer)，拿到真实token
            String authToken = authHeader.substring(tokenHead.length());

            //拿到token里面的username
            String username = securityJwtUtil.getUsername(authToken);

            //然后看看上下文中是否有我们以这个username为标识的主体,没有去new一个
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                //缓存里查询用户，不存在需要重新登陆
                LoginUser loginUser = (LoginUser) loginUsersService.loadUserByUsername(username);

                //拿到用户信息后验证用户信息与token
                if (securityJwtUtil.validateToken(authToken, loginUser)) {

                    //组装authentication对象，构造参数是Principal Credentials与Authorities
                    //后面的拦截器里面会用到grantedAuthorities 方法
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                    //将authentication信息放入到上下文对象中, 这样后面的过滤器看到我们上下文对象中有authentication对象，就相当于我们认证过了
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    log.info("校验token-登录成功, user: {}", username);
                }
            }
        }
        chain.doFilter(request, response);
    }

}
